﻿using System;
using System.Diagnostics;
using System.IO;

namespace HelperLib
{
   public class Logger
   {
      private readonly StreamWriter myLogWriter;
      private readonly string filepath;

      public Logger(string filepath)
      {
         this.filepath = filepath;
         Debug.WriteLine(DateTime.Now + " Debugging started.");

         try
         {
            myLogWriter = File.AppendText(@filepath);
            Debug.WriteLine(DateTime.Now + " Logfile created.");

            write("----------------------------------------------------------");
            write("New Logging-Session " + DateTime.Now);
         }
         catch (IOException exeption)
         {
            Debug.WriteLine(DateTime.Now + " " + exeption.Message);
         }
      }

      /// <summary>
      /// Call to close the stream to the logfile.
      /// </summary>
      public void closeLog()
      {
         if (myLogWriter == null)
         {
            Debug.WriteLine(DateTime.Now + " - Error - Logfile not initialized.");
            return;
         }
         if (!File.Exists(@filepath))
         {
            Debug.WriteLine(DateTime.Now + " - Error - Logfile does not exist.");
            return;
         }

         write(DateTime.Now + " Logging finished.");
         myLogWriter.Close();
      }

      /// <summary>
      /// Write information to the logfile.
      /// </summary>
      /// <param name="logEvent">String to be written into the logfile</param>
      public void writeLogEvent(string logEvent)
      {
         if (myLogWriter == null)
         {
            Debug.WriteLine(DateTime.Now + " - Error - Logfile not initialized.");
            return;
         }
         if (!File.Exists(@filepath))
         {
            Debug.WriteLine(DateTime.Now + " - Error - Logfile does not exist.");
            return;
         }

         write(DateTime.Now + " " + logEvent);
      }

      private void write(string logString)
      {
         myLogWriter.WriteLine(logString);
         myLogWriter.Flush();
         Debug.WriteLine(logString);
      }
   }
}
